# tests/conftest.py
import pytest
import json
from unittest.mock import MagicMock
from src.api.openai_api import OpenAIClient

# --- AI 回答校验器 (保持不变) ---
class AIResponseValidator:
    # ... (这部分代码保持不变) ...
    @staticmethod
    def validate(query, response):
        if "论文类" in query:
            try:
                # 为了校验，我们解码它
                data = json.loads(response)
                assert "title" in data
                assert "text" in data
                assert "name" in data
                # 检查内容是否是中文
                assert any("\u4e00" <= char <= "\u9fff" for char in data["title"])
                return True
            except (json.JSONDecodeError, AssertionError):
                pytest.fail(f"论文类回答格式错误或内容不符。收到的回答: {response}")
        # ... (其他类型的校验保持不变) ...
        elif "选择类" in query:
            if "正确答案是" not in response:
                pytest.fail(f"选择类回答格式错误，应包含'正确答案是'。收到的回答: {response}")
            return True

        elif "填空类" in query:
            try:
                json.loads(response)
                pytest.fail(f"填空类回答不应是JSON格式。收到的回答: {response}")
            except json.JSONDecodeError:
                pass  # 正常情况
            if "正确答案是" in response:
                 pytest.fail(f"填空类回答不应包含'正确答案是'。收到的回答: {response}")
            return True
        
        return True

# --- Pytest Fixtures (修正部分) ---
@pytest.fixture
def mock_openai_client() -> MagicMock:
    """
    创建一个模拟的OpenAIClient。
    它会根据传入的 query 动态返回预设的、符合格式的回答。
    """
    mock_client = MagicMock(spec=OpenAIClient)

    def mock_get_answer(history_paper, model="moonshot-v1-8k", temperature=0.3):
        user_query = history_paper[-1]['content']
        
        if "论文类" in user_query:
            # 关键修改：添加 ensure_ascii=False
            response_content = json.dumps({
                "title": "模拟论文标题",
                "text": "这是模拟的论文内容...",
                "name": "模拟文件名.docx"
            }, ensure_ascii=False) # <--- 在这里添加
        elif "选择类" in user_query:
            response_content = "1. 正确答案是 B. SMTP。"
        elif "填空类" in user_query:
            response_content = "1. DNS的端口号是53,FTP的端口号是21"
        else:
            response_content = "这是一个通用的模拟回答。"
            
        AIResponseValidator.validate(user_query, response_content)

        return response_content

    mock_client.get_answer.side_effect = mock_get_answer
    
    return mock_client

@pytest.fixture
def ai_validator():
    """提供AI回答校验器实例"""
    return AIResponseValidator()